// Utility functions for handling switch/case nodes

/**
 * Generate an anchor ID for a node.
 * @param {string} nodeId - The base node ID.
 * @param {string} type - The type of anchor ("IF", "ELSE", or case index).
 * @param {number} index - The case index (1-based).
 * @returns {string} The anchor ID string.
 */
function getAnchorId(nodeId, type, index) {
  let anchorType;
  if (type === "IF") {
    anchorType = "source_if";
  } else if (type === "ELSE") {
    anchorType = "source_else";
  } else {
    anchorType = `case_${index}`;
  }
  return `${nodeId}_${anchorType}`;
}

/**
 * Get the anchor ID based on the choice index.
 * @param {string} nodeId - The base node ID.
 * @param {number} chooseIndex - The choice index. -1 for ELSE, 0 for IF, >0 for ELIF.
 * @returns {string} The anchor ID string.
 */
function getAnchorIdByChooseIndex(nodeId, chooseIndex) {
  let anchorType;
  if (chooseIndex === -1) {
    anchorType = "ELSE";
  } else if (chooseIndex === 0) {
    anchorType = "IF";
  } else {
    anchorType = "ELIF";
  }
  // The index argument in getAnchorId is 1-based
  return getAnchorId(nodeId, anchorType, chooseIndex + 1);
}

/**
 * Get the list of cases/options (if/elif/else) for a node.
 * @param {object} node - The node object containing properties.
 * @returns {Array} Array of case descriptor objects.
 */
function getCaseList(node) {
  const result = [];
  // Defensive: use empty object if missing
  const options = node?.properties?.options ?? {};

  // "if" cases
  if (Array.isArray(options.if)) {
    for (let idx = 0; idx < options.if.length; idx++) {
      result.push({
        type: idx === 0 ? "IF" : "ELIF",
        label: `CASE ${idx + 1}`,
        value: options.if[idx],
      });
    }
  }
  // "else" case
  if (options.else) {
    result.push({
      type: "ELSE",
      value: options.else,
    });
  }
  return result;
}

// Export as a module
const SwitchHelpers = Object.freeze({
  getAnchorId,
  getAnchorIdByChooseIndex,
  getCaseList,
  [Symbol.toStringTag]: "Module",
});

export { SwitchHelpers as S };